#!/usr/bin/env python3
# -*- encoding: utf-8 -*-
'''
@author: yuejl
@application:
@contact: lewyuejian@163.com
@file: continuous_load.py
@time: 2021/11/14 0014 15:15
@desc: 加载
'''
import yaml, json, os
from integratior_service import BASE_PATH as base_path
from configparser import ConfigParser
from integratior_service.controllers.common.exceptions import JsonDecodeError, FileFormatError, FileFormatNotSupported, \
    FileNotFound


class FileUtil:

    @staticmethod
    def _get_file_suffix(file_path):
        suffix = file_path.split('.', 1)[1]
        return suffix

    @staticmethod
    def _load_yml(file_path):
        with open(file_path, 'r', encoding='utf-8') as file_object:
            yml_content = yaml.load(file_object, Loader=yaml.CLoader)
            return yml_content

    @staticmethod
    def _load_json(file_path):
        with open(file_path, 'r', encoding='utf-8') as file_object:
            try:
                json_content = json.load(file_object)
            except JsonDecodeError:
                errMsg = u"JsonDecodeError:Json file format error! \"{}\"".format(file_path)
                raise FileFormatError(errMsg)
            return json_content

__FileUtils = FileUtil

def load_file(file_name, path = base_path):
    data = None
    # 判断不是绝对路径
    if not os.path.isabs(file_name):
        folder_path = os.listdir(path)
        for file in folder_path:
            absolute_path = os.path.join(path, file)
            if os.path.isdir(absolute_path):
                data = load_file(file_name, absolute_path)
                # 文件不存在或者文件内容为空，都返回none
                if data is not None:
                    return data
            elif file_name == file:
                if __FileUtils._get_file_suffix(file_name) in ['yml', 'yaml']:
                    data = __FileUtils._load_yml(absolute_path)
                elif __FileUtils._get_file_suffix(file_name) == 'json':
                    data = __FileUtils._load_json(absolute_path)
                else:
                    raise FileFormatNotSupported(f"file format not supported >>> {file_name}!")
                return data
    else:
        if not os.path.isfile(file_name):
            raise FileNotFound(f"file does not exist >>> {file_name}!")
        else:
            suffix = os.path.splitext(file_name)[1].lower()
            if suffix in ['.yml', '.yaml']:
                data = __FileUtils._load_yml(file_name)
            elif suffix == '.json':
                data = __FileUtils._load_json(file_name)
            else:
                raise FileFormatNotSupported(f"file format not supported >>> {file_name}!")
            return data

class loadConfPaser(ConfigParser):
    '''
           重写 configparser 中的 optionxform 函数
           解决 .ini 文件中的 键option 自动转为小写的问题
   '''
    def __init__(self, defaults = None):
        ConfigParser.__init__(self, defaults=defaults)

    def optionxform(self, optionstr: str) -> str:
        return optionstr

